﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SaunaClient.Model.Network;
using SaunaDTestSuite.SaunaClient.View;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace SaunaClient.View
{
    public partial class Form1 : Form
    {
        private IFtpFactory ftpFactory;
        private IFtpDaoGateway ftps;
        private NetworkSetting networkSetting;
        private const string FTP_SSL = "FtpSsl";
        private string CONFIG_FILE_NAME = @"SaunaConfig.ini";
        private string serverDirectory;
        private string localDirectory;

        public Form1()
        {
            InitializeComponent();

            // Read Sauna configuration file and create network setting 
            networkSetting = (NetworkSetting)ReadFromFile(CONFIG_FILE_NAME);
            if (networkSetting == null)
            {
                // When Sauna configuration file does not exist, create network setting with default values
                networkSetting = new NetworkSetting();
            }

            lblServerDirectory.Text = networkSetting.FtpServerDirectory;
            serverDirectory = networkSetting.FtpServerDirectory;
            lblLocalDirectory.Text = networkSetting.FtpLocalDirectory;
            localDirectory = networkSetting.FtpLocalDirectory;

            // Make ftp communication handler
            ftpFactory = new FtpFactoryImplementation();
            ftps = ftpFactory.Make(FTP_SSL, networkSetting);


        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.ShowDialog();
            
            // Gets the file and stores them in a list
            lstUserFiles.BeginUpdate();
            lstUserFiles.Items.Add(openFileDialog1.FileName);
            lstUserFiles.EndUpdate();

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            txtboxFilePath.Text = openFileDialog1.FileName;

        }

        //private void button2_Click(object sender, EventArgs e)
        //{   
        //    ftps.Upload(System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"\", System.IO.Path.GetFileName(openFileDialog1.FileName), serverDirectory);
            
        //}

        private void ServerFileList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void LocalFileList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            String selectedFileName = lstServerFiles.SelectedItem.ToString();
            string[] arraySelectedFiles = selectedFileName.Split(new Char[] { '\n' });
            string fileName;
            string fileRealName; 
            foreach (string oneFile in arraySelectedFiles)
            {
                fileName = oneFile.Substring(39);
                fileRealName = fileName.TrimEnd(new Char[] { '\r' });
                ftps.Download(serverDirectory, fileRealName, localDirectory);
            }
            lstUserFiles.BeginUpdate();
            lstUserFiles.Items.Add(selectedFileName);
            lstUserFiles.EndUpdate();

        }

        private void button4_Click(object sender, EventArgs e)
        {   // Updates the list on the server
            txtboxServerFiles.Text = ftps.GetServerFileList("/");

            Array arrayFiles = txtboxServerFiles.Text.Split(new Char[] {'\n' });

           // listItem n
            // Gets the file and stores them in a list

           // lstServerFiles.BeginUpdate();
           // lstServerFiles.Items.Add(ftps.GetServerFileList("/"));
            //lstServerFiles.EndUpdate();

            foreach (String fileName in arrayFiles)
            {
                lstServerFiles.BeginUpdate();
                lstServerFiles.Items.Add(fileName);
                lstServerFiles.EndUpdate();
            }

            //lstServerFiles.BeginUpdate();

            //for (int x = 1; x <= 5; x++)
            //{
            //    lstServerFiles.BeginUpdate();
            //    lstServerFiles.Items.Add(ftps.GetServerFileList("/"));
            //}
            //lstServerFiles.EndUpdate();
        }

        private void lstUserFiles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void serverList_TextChanged(object sender, EventArgs e)
        {

        }

        private void lstServerFiles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Read ftp base setting from file
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public object ReadFromFile(string filePath)
        {
            object obj = null;
            try
            {
                using (Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    IFormatter formatter = new BinaryFormatter();
                    obj = formatter.Deserialize(stream);
                }
            }
            catch (FileNotFoundException ex)
            {
                // Write error.
                Console.WriteLine(ex);
            }
            return obj;
        }

        /// <summary>
        /// Option menu event handler
        /// </summary>
        /// <param name="sender">Event sender object</param>
        /// <param name="e">Event arguments</param>
        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClientOptionForm clientOptionForm = new ClientOptionForm(networkSetting);

            if (clientOptionForm.ShowDialog() == DialogResult.OK)
            {
                networkSetting.Copy(clientOptionForm.networkSetting);

                lblServerDirectory.Text = networkSetting.FtpServerDirectory;
                serverDirectory = networkSetting.FtpServerDirectory;
                lblLocalDirectory.Text = networkSetting.FtpLocalDirectory;
                localDirectory = networkSetting.FtpLocalDirectory;

            }

            //textFtpHostAddr.Text = networkSetting.FtpHostAddress;
            //textFtpUserName.Text = networkSetting.FtpUserName;
            //textFtpPassword.Text = networkSetting.FtpPassword;
            //textFtpServerDirectory.Text = networkSetting.FtpServerDirectory;
            //textFtpLocalDirectory.Text = networkSetting.FtpLocalDirectory;
            //checkBoxFtpSsl.Checked = networkSetting.FtpSsl;
            //textTcpHostAddr.Text = networkSetting.TcpHostAddress;
            //textLogFileDirectory.Text = networkSetting.LogFileDirectory;
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            ftps.Upload(System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"\", System.IO.Path.GetFileName(openFileDialog1.FileName), serverDirectory);
        }


    }
}
